package com.lyk.coursearrange.controller;


import com.baomidou.mybatisplus.extension.api.R;
import com.lyk.coursearrange.common.log.annotation.Log;
import com.lyk.coursearrange.common.log.enums.OperationType;
import com.lyk.coursearrange.entity.GradeInfo;
import com.lyk.coursearrange.service.GradeInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lequal
 * @since 2020-03-20
 */
@RestController
@RequestMapping("/grade")
@RequiredArgsConstructor
public class GradeInfoController {

    private final GradeInfoService gradeInfoService;

    @GetMapping("getGrade")
/*    @Log(title = "查询年纪", operationType = OperationType.SELECT)*/
    public R<List<GradeInfo>> getGrade() {
        List<GradeInfo> gradeInfos = getTree();
        return R.ok(gradeInfos);
    }


    public List<GradeInfo> getTree() {
        //数据查询
        List<GradeInfo> list = gradeInfoService.list();
        //新建一个用于接收数据的list
        List<GradeInfo> resultList = new ArrayList<>();
        for (GradeInfo result : list) {
            if (result.getParentId() == 0) {
                //调用方法给子类添加数据
                resultList.add(getMenuTree(result, list));
            }
        }
        return resultList;
    }

    /**
     * 递归查询子节点
     * @return 根节点信息
     */
    private GradeInfo getMenuTree(GradeInfo result, List<GradeInfo> list) {
        for (GradeInfo sysDepartManage : list) {
            //如果父类主键等于传过来实体类的ID
            if (sysDepartManage.getParentId().equals(result.getId())) {
                if (result.getChildren() == null) {
                    result.setChildren(new ArrayList<>());
                }
                // 递归调用
                result.getChildren().add(getMenuTree(sysDepartManage, list));
            }
        }
        return result;
    }


}

